package com.example.aigc_education.controller.common;

import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.constant.CacheConstants;
import com.example.aigc_education.constant.Constants;

import com.example.aigc_education.utils.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RequestMapping("/sms")
@RestController
public class SmsController {
    @Resource
    private SmsUtils smsUtils;

    @Resource
    private RedisCache redisCache;

    /**
     * 发送短信验证码
     * @param phone 手机号
     * @return 返回发送结果
     */
    @GetMapping("/{phone}")
    public ResultUtil sendMessage(@PathVariable String phone) {
        ResultUtil result = ResultUtil.success();
        if (StringUtils.isAnyBlank(phone)) {
            throw new BusinessException("手机号为空");
        }
        // 从redis中查看有没有该手机号的验证码
        String verifyCode = redisCache.getCacheObject(CacheConstants.SMS_CODE_KEY + phone);
        //有手机号码证明已经发送过了,这次就要刷新
        if (!StringUtils.isAnyBlank(verifyCode)) {
            //删除原来的验证码
            smsUtils.delete(phone);
            // 生成新的验证码
            String newVerifyCode = RandomUtils.getSixBitRandom();
            // 重新发送短信
            Boolean isSend = smsUtils.sendMessage(newVerifyCode, phone);
            if (!isSend) {
                throw new BusinessException("短信重新发送失败");
            }
//            result.put("code", newVerifyCode);
//            return result;
            return ResultUtil.success("短信重新发送成功");
        }

        // 如果redis没有该手机号验证码，则获取验证码并发送短信
        verifyCode = RandomUtils.getSixBitRandom(); // 获取六位验证码
        Boolean isSend = smsUtils.sendMessage(verifyCode, phone); // 调用短信发送模板
        if (!isSend) { // 如果发送成功，则将对应手机号验证码存入redis中，设置5分钟内有效
            throw new BusinessException("短信发送失败");
        }
//        result.put("code",verifyCode);
//        return result;
        return ResultUtil.success("短信发送成功");
    }

}
